package com.graduation.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.base.Result;
import com.graduation.table.administrators.entity.Administrators;
import com.graduation.table.administrators.service.IAdministratorsService;
import com.graduation.table.authority.entity.Authority;
import com.graduation.table.authority.service.IAuthorityService;
import com.graduation.table.role.entity.Role;
import com.graduation.table.role.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private IAdministratorsService administratorsService;
    @Resource
    private IAuthorityService authorityService;
    @Resource
    private IRoleService roleService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("X-Access-Header");
//        response.setContentType("application/json;charset=UTF-8");
        String uri = request.getRequestURI();
        if (!StringUtils.isEmpty(uri) &&
                uri.equals("/clazz/download") || uri.equals("/clazz/upload") || uri.equals("/hotSpots/release/code")){
            return true;
        }
        if (StringUtils.isEmpty(userId)) {
            // 为未携带用户信息
            response.getWriter().print(JSON.toJSONString(Result.error(403, "用户不存在")));
            return false;
        }
        //通过判断用户是否有该请求路径的权限
        Administrators administrators = administratorsService.getById(userId);
        if (Objects.isNull(administrators)){
            response.getWriter().print(JSON.toJSONString(Result.error(403, "用户不存在")));
            return false;
        }

        log.debug(uri);
        //获取数据库对应接口路径的权限
        Authority authority =authorityService.getOne(new LambdaQueryWrapper<Authority>()
                .eq(Authority::getUri,uri));
        // 如果不存在对该路径进行接口权限配置，则放行
        if (null == authority) {
            return true;
        }
        //获取用户对应的角色
        Role role = roleService.getOne(new LambdaQueryWrapper<Role>()
                .inSql(Role::getId,"select role_id from administrator_role_relation where administrators_id = '"+userId+"'"));
        //用户没有角色
        if (Objects.isNull(role)){
            response.getWriter().write(JSON.toJSONString(Result.error(403, "用户无权限")));
            return false;
        }
        List<Authority> list = authorityService.list(new LambdaQueryWrapper<Authority>()
                .inSql(Authority::getId,"select authority_id from role_authority_relation where role_id = '"+role.getId()+"'"));
        // 如果存在则判断该用户是否存在接口权限,存在则放行
        if (null != list && list.size()>0){
            for (Authority authority1:list){
                if (!StringUtils.isEmpty(authority1.getUri()) && authority1.getUri().equals(uri)){
                    return true;
                }
            }
        }
        response.getWriter().write(JSON.toJSONString(Result.error(403, "用户无权限")));

        return false;
    }
}
